﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MediaGarden.Services;
using Orchard.Themes;
using Orchard.ContentManagement;
using Orchard.DisplayManagement;
using Orchard;
using MediaGarden.Models;
using Orchard.Mvc;

namespace MediaGarden.Controllers
{
    public class EmbeddingController : Controller
    {
        private readonly IMediaGardenService _mediaGardenService;

        public EmbeddingController(
            IOrchardServices services,
            IMediaGardenService mediaGardenService,
            IShapeFactory shapeFactory
            )
        {
            Services = services;
            _mediaGardenService = mediaGardenService;
            Shape = shapeFactory;
        }
        public IOrchardServices Services { get; set; }
        public dynamic Shape { get; set; }

        [Themed(true)]
        public ActionResult Embed(int id, int? width, int? height)
        {
            var routeValues = ControllerContext.RouteData.Values;
            var item = Services.ContentManager.Get(id);
            if (item==null) return HttpNotFound();

            var media = item.As<IMediaContentItem>();
            if (media == null) return HttpNotFound();

            // TODO: Support autoplay / playlistFormat if we really want them
            var autoplay = false;
            var playlistFormat = "Default";

            // TODO: Some sort of prevention of DOS by creating images at all different sizes!
            var shape = Shape.Media(MediaItem: media, Width: width ?? 640, Height: height ?? 480,
                AutoPlay: autoplay, PlaylistFormat: playlistFormat);

            // Use our stripped-down layout
            Services.WorkContext.Layout.Metadata.Alternates.Add("Layout_Embedding");

            // Let Orchard handle the shape from here on
            return new ShapeResult(this, shape);
        }

    }
}